package com.tanhua.dubbo.utils;

import com.tanhua.domain.mongo.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

@Component
public class IdService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 1、自定义mongo数据库表
     *     表名
     *     此表的主键
     * 2、获取某个表的自增id
     *   IdService.getNextId("表明");
     *
     */
    public Long getNextId(String collName) {

        //根据表名查询
        Query query = new Query(Criteria.where("collName").is(collName));

        //更新
        Update update = new Update();
        //inc : 将制定字段 + 1
        update.inc("seqId", 1);

        //本次更新的配置
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.upsert(true);   //没有查找数据，自动保存
        options.returnNew(true); //查询之后，获取最新的数据结果

        Sequence sequence = mongoTemplate.findAndModify(query, update, options, Sequence.class);
        return sequence.getSeqId();
    }
}